import React, { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View,  Image } from '@tarojs/components'
import { connect } from 'react-redux'
import classnames from 'classnames'
import CarInfo from '@/components/CarInfo'
import GoodList from '@/components/GoodsView/GoodList'
import MoreView from '@/components/GoodsView/MoreView'
import StateList from '@/components/StateList'
import CouponView from '@/components/CouponView'
import { fetchAnnualCardUse, fetchAnnualCardApply } from '@/api/annual'
import dayjs from 'dayjs'
import './index.scss'

interface State {
  couponInfo: any,
  serviceTime: any,
	selectStore:object
}

@connect<any>(({ car, location }) => ({
  car: car.carInfo.currentCar,
  store: location.storeLocation
}))
export default class AnnualUseIndex extends Component<any> {
  $instance = getCurrentInstance();
	protected __data__: any
  constructor () {
    super(...arguments)
    this.state = {
      couponInfo: null,
      serviceTime: null,
			selectStore:{}
    }
		this.__data__ = process.env.TARO_ENV === 'weapp' ? '__data__' : 'data'
  }
  private formData: any = {}
  private isNeedUpdateTime: boolean = false
  state: State

  UNSAFE_componentWillMount() { }

  async componentDidMount() {
    await this.getList()
  }
  UNSAFE_componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() {
    try {
      Taro.removeStorageSync('BOOKING_TIME')
    } catch (e) {
      Taro.removeStorageSync('BOOKING_TIME')
    }
  }
  componentDidShow() {
    if (this.isNeedUpdateTime) {
      let serviceTime = Taro.getStorageSync('BOOKING_TIME')
      this.setState({
        serviceTime
      })
    }
		let pages = Taro.getCurrentPages();
		let currentPage = pages[pages.length - 1]; // 获取当前页面
		if (currentPage[this.__data__].selectStore) { // 获取值
			this.setState({ selectStore: currentPage[this.__data__].selectStore })
			console.log('selectStore',currentPage[this.__data__].selectStore)
		}
  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  async getList() {
    const { formData } = this.$instance.router.params
    this.formData = JSON.parse(formData)
    Taro.showLoading({ title: '加载中' })
    try {
      let res = await fetchAnnualCardUse(formData)
      let { data } = res
      if (data.success) {
        this.setState({
          couponInfo: data.data
        })
      }
    } catch (e) {
      console.log(e)
    } finally {
      Taro.hideLoading()
    }
  }
  private createOrderStatus: boolean = false
  // 提交订单
  async sendOrder() {
    let { serviceTime, couponInfo,selectStore } = this.state
		if (!selectStore.storeCode) {
      Taro.showToast({
        icon: 'none',
        title: '请选择预约门店',
        duration: 2000
      })
      return
    }
    if (!serviceTime) {
      Taro.showToast({
        icon: 'none',
        title: '请选择预约时间',
        duration: 2000
      })
      return
    }
    try {
      Taro.showLoading({ title: '提交中' })
      let res = await fetchAnnualCardApply({
        couponItemIds: JSON.stringify(couponInfo.couponItemIds),
        time: serviceTime,
        carLicense: this.props.car.carLicense,
        storeCode: this.props.store.storeCode
      })
      if (!res.data.success) throw Error(res.data.data.message)
      Taro.redirectTo({
        url: '/pages/order/details/index?orderNumber=' + res.data.data.orderNumber
      })

    } catch (error) {
      Taro.showToast({
        icon: 'none',
        title: error.message,
        duration: 2000
      })
    }
  }
	// 选择下单门店
	gotoSelectStores() {
		const { couponInfo } = this.state
		console.log('couponInfo.couponItemIds',couponInfo.couponItemIds)
		console.log(`/pages/store/platform/index?couponItemIds=${(String(couponInfo.couponItemIds))}&type=booking`)
		Taro.navigateTo({
			url: `/pages/store/platform/index?couponItemIds=${(couponInfo.couponItemIds)}&type=booking`
		})
	}
  handleBooking() {
    const { couponInfo, serviceTime ,selectStore} = this.state
    const { formData } = this.$instance.router.params
		if (!selectStore.storeCode) {
			Taro.showToast({
				icon: 'none',
				title: '请选择预约门店',
				duration: 2000
			})
			return
		}
    let goodsData: Array<any> = []
    let goods: Array<any> = couponInfo.items
    goods.map(i => {
      let { goodsId, goodsSkuId, type } = i.goods
      goodsData.push({
        goodsId,
        goodsSkuId,
        number: i.useNumber,
        type
      })
    })
		let params = {
			storeCode:selectStore.storeCode,
			storeName:selectStore.storeName,
		}
    this.isNeedUpdateTime = true
    let url = '/pages/order/booking/index?from=annual&order=' + JSON.stringify(goodsData) + '&formData=' + formData+'&selectStore=' +JSON.stringify(params)
    if (serviceTime) {
      url += '&applyTime=' + serviceTime
    }
    Taro.navigateTo({ url })
  }
  render() {
    const { store } = this.props
		console.log('store',store)
    let { couponInfo, serviceTime,selectStore } = this.state
    const filterDate = unixTimestamp => {
      return !unixTimestamp ? '请选择时间' : dayjs.unix(unixTimestamp).format('YYYY-MM-DD HH:mm')
    }
    return (
      <View className='annual-use-index'>
        <CarInfo loaded disabled styleView='3' />
        <View className='margin-top20'>
          {/* {store && store.storeName && <StateList name='预约门店' context={store.storeName} />} */}
					<StateList handle={this.gotoSelectStores.bind(this)} name='预约门店' context={selectStore.storeName || '请选择预约门店'} contextIcon='icon-shaixuanxialajiantou'/>
          { selectStore.address && <StateList name='门店地址' baseline context={selectStore.address} contextIconColor='#12B3FF' contextIconSize='44' contextIcon='icon-zu28' />}
          { <StateList name='预约时间' baseline context={filterDate(serviceTime)} contextIconColor='#CCCCCC' contextIconSize='26' handle={this.handleBooking.bind(this)} contextIcon='icon-jiantourukou' />}
        </View>
        {
          couponInfo && couponInfo.items && <View className='goods-item margin-top20'>
            {

              couponInfo.items.map((v, index) => {
                v.goods.number = v.useNumber
                return <View key={'good' + index} className='li'><GoodList list={v.goods} /></View>
              })
            }
          </View>
        }
        <View className='handle-cont'>
          <View className='btn' onClick={this.sendOrder.bind(this)}>确认预约</View>
        </View>
      </View>
    )
  }
}
